import { defineStore } from 'pinia'
import { ConfigType, PackagesStoreType, PackagesType } from './packagesStore.d'
import { packagesList } from '@/packages/index'
import { StorageEnum } from '@/enums/storageEnum'
import { getLocalStorage, setLocalStorage } from '@/utils'
import { domainid } from '@/utils/cloud/utils'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import { updateConfigApi } from '@/api/cloud/config'
import { ExternalResourceType } from '@/views/project/items/index.d'

// 组件 packages
export const usePackagesStore = defineStore({
  id: 'usePackagesStore',
  state: (): PackagesStoreType => ({
    packagesList: Object.freeze(packagesList),
    newPhoto: undefined
  }),
  getters: {
    getPackagesList(): PackagesType {
      return this.packagesList
    }
  },
  actions: {
    addPhotos(newPhoto: ConfigType, index: number) {
      this.newPhoto = newPhoto
      this.packagesList.Photos.splice(index, 0, newPhoto)
    },
    setPhotos(photos: ConfigType[]) {
      this.packagesList.Photos.forEach((item: ConfigType, index: number) => {
        if (item.category === 'Private' && !item.disabled) {
          this.deletePhotos(item, index)
        }
      })
      photos.forEach((item: ConfigType) => this.addPhotos(item, 1))
    },
    async deletePhotos(photoInfo: ConfigType, index: number) {
      const chartEditStore = useChartEditStore()
      const { content, datasource, name } = chartEditStore.getEditProjectInfo
      if (!content!.externalResource) content!.externalResource = {} as ExternalResourceType

      if (!content!.externalResource!.images) content!.externalResource!.images = []
      content!.externalResource!.images = content!.externalResource!.images.filter(
        (item: any) => item.name !== photoInfo.title
      )

      let updateData: any = {
        app_application: 'page_designer',
        app_datasource: datasource,
        app_name: name,
        domain_id: domainid(true),
        ...content
      }
      const res = await updateConfigApi(updateData)
      if (res.code === 200) {
        this.packagesList.Photos.splice(index, 1)
      }
      // const StoreKey = StorageEnum.GO_USER_MEDIA_PHOTOS
      // const userPhotosList = getLocalStorage(StoreKey)
      // userPhotosList.splice(index - 1, 1)
      // setLocalStorage(StoreKey, userPhotosList)
    }
  }
})
